package com.sgcc.activiti.service.impl;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.sgcc.activiti.domain.OContentAd;
import com.sgcc.activiti.domain.OContentAppSchema;
import com.sgcc.activiti.mapper.OContentAdMapper;
import com.sgcc.activiti.mapper.OContentAppSchemaMapper;
import com.sgcc.activiti.service.IProcessService;
import com.sgcc.common.core.constant.Constants;
import com.sgcc.common.core.text.Convert;
import com.sgcc.common.core.text.UUID;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.redis.service.RedisService;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.domain.SysRole;
import com.sgcc.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAdSchemaMapper;
import com.sgcc.activiti.domain.OContentAdSchema;
import com.sgcc.activiti.service.IOContentAdSchemaService;
import org.springframework.util.CollectionUtils;

/**
 * 广告管理维护方案Service业务层处理
 *
 * @author sgcc
 * @date 2021-04-07
 */
@Service
public class OContentAdSchemaServiceImpl implements IOContentAdSchemaService {
    @Autowired
    private OContentAdSchemaMapper oContentAdSchemaMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private OContentAdMapper oContentAdMapper;

    @Autowired
    private OContentAppSchemaMapper oContentAppSchemaMapper;

    /**
     * 查询广告管理维护方案
     *
     * @param id 广告管理维护方案ID
     * @return 广告管理维护方案
     */
    @Override
    public OContentAdSchema selectOContentAdSchemaById(String id) {
        return oContentAdSchemaMapper.selectOContentAdSchemaById(id);
    }

    /**
     * 查询广告管理维护方案列表
     *
     * @param oContentAdSchema 广告管理维护方案
     * @return 广告管理维护方案
     */
    @Override
    public List<OContentAdSchema> selectOContentAdSchemaList(OContentAdSchema oContentAdSchema) {
        List<OContentAdSchema> list = oContentAdSchemaMapper.selectOContentAdSchemaList(oContentAdSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    if (null == item.getProcessKey()) {
                        item.setType("todo");
                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    /**
     * 新增广告管理维护方案
     *
     * @param oContentAdSchema 广告管理维护方案
     * @return 结果
     */
    @Autowired
    private RedisService redisService;
    private String time = DateUtils.dateTime();

    @Override
    public int insertOContentAdSchema(OContentAdSchema oContentAdSchema) {
        Integer num = redisService.getCacheObject("activiti:OContentAdSchemaServiceImpl:insertOContentAdSchema");
        if (null == num) {
            num = 0;
        }
//        OContentAd contentAd=oContentAdMapper.selectOContentAdById(oContentAdSchema.getId());
        num++;
        if (!time.equals(DateUtils.dateTime())) {
            num = 1;
            time = DateUtils.dateTime();
        }
        redisService.setCacheObject("activiti:OContentAdSchemaServiceImpl:insertOContentAdSchema", num, 30L, TimeUnit.DAYS);
        NumberFormat f = new DecimalFormat("00000");
        String id = DateUtils.dateTimeNow() + f.format(num);
        oContentAdSchema.setId(id);
        OContentAdSchema old = oContentAdSchemaMapper.selectOContentAdSchemaById(id);
        if (null != old) {
            return 0;
        }
        if (oContentAdSchema.getNewId() == null) {
            OContentAd oContentAd2 = new OContentAd();
            BeanUtils.copyProperties(oContentAdSchema, oContentAd2);
            oContentAd2.setAppNo(null);
            oContentAd2.setSpareThree(null);
            // 发布状态,advIssueState,1	已上架 2	已下架 3.发布失败
            oContentAd2.setAdState("1");
            oContentAd2.setRemarks("新增广告发布成功");
            oContentAd2.setSpareFive(null);
            oContentAd2.setId(null);
            oContentAd2.setCreateBy(null);
            oContentAd2.setCreateDate(null);
            oContentAd2.setUpdateBy(null);
            oContentAd2.setUpdateDate(null);
            oContentAd2.setDelFlag("0");
            oContentAd2.setSpareFour(oContentAdSchema.getServiceType());
            oContentAd2.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            oContentAd2.setAppNo(oContentAd2.getId());
            oContentAdMapper.insertOContentAd(oContentAd2);
            oContentAdSchema.setAppNo(oContentAd2.getId());
        }

        int i = oContentAdSchemaMapper.insertOContentAdSchema(oContentAdSchema);
        if (i > 0) {
//            contentAd.setAppNo(id);
//            oContentAdMapper.updateOContentAd(contentAd);
            OContentAdSchema obj = oContentAdSchemaMapper.selectOContentAdSchemaById(id);
            try {
                processService.submitApply(obj, "content_ad");
            } catch (Exception e) {
                e.printStackTrace();
            }
            oContentAdSchemaMapper.updateOContentAdSchema(obj);
        }
        return i;
    }

    /**
     * 修改广告管理维护方案
     *
     * @param oContentAdSchema 广告管理维护方案
     * @return 结果
     */
    @Override
    public int updateOContentAdSchema(OContentAdSchema oContentAdSchema) {
        int i = oContentAdSchemaMapper.updateOContentAdSchema(oContentAdSchema);
        if (i > 0) {
            OContentAdSchema obj = oContentAdSchemaMapper.selectOContentAdSchemaById(oContentAdSchema.getId());
            System.out.println(obj.toString());
//            try {
//                processService.submitApply(obj, "content_ad");
//                System.out.println("添加流程执行完毕");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            oContentAdSchemaMapper.updateOContentAdSchema(obj);
        }
        return i;
    }

    /**
     * 批量删除广告管理维护方案
     *
     * @param ids 需要删除的广告管理维护方案ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdSchemaByIds(String[] ids) {
        return oContentAdSchemaMapper.deleteOContentAdSchemaByIds(ids);
    }

    /**
     * 删除广告管理维护方案信息
     *
     * @param id 广告管理维护方案ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdSchemaById(String id) {
        return oContentAdSchemaMapper.deleteOContentAdSchemaById(id);
    }

    @Override
    public List<OContentAdSchema> selectOContentAdSchemaListProcess(OContentAdSchema oContentAdSchema) {
        SysUser user = tokenService.getLoginUser().getSysUser();
        List<String> ids = new ArrayList<String>();
        for (SysRole role : user.getRoles()) {
            ids.add(role.getRoleKey());
        }
        oContentAdSchema.setRoleKey(ids);
        oContentAdSchema.setAssignee(user.getUserName());

        List<OContentAdSchema> list = oContentAdSchemaMapper.selectOContentAdSchemaListProcess(oContentAdSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
//                    if (null == item.getProcessKey()) {
                    item.setType("todo");
//                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    @Override
    public List<OContentAdSchema> selectOContentAdSchemaListSubmitist(OContentAdSchema oContentAdSchema) {
//        return oContentAdSchemaMapper.selectOContentAdSchemaListSubmitist(oContentAdSchema);
        List<OContentAdSchema> list = oContentAdSchemaMapper.selectOContentAdSchemaListSubmitist(oContentAdSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
//                    if (null == item.getProcessKey()) {
//                    item.setType("todo");
//                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    @Override
    public Integer selectOContentAdByNewId(String newId) {
        return oContentAdSchemaMapper.selectOContentAdByNewId(newId);
    }

    @Override
    public int updateStatus() {
        OContentAdSchema oContentAdSchema = new OContentAdSchema();
        oContentAdSchema.setProcessId("f3");
        oContentAdSchema.setSpareThree("true");
        List<OContentAdSchema> oContentAdSchemas = oContentAdSchemaMapper.selectOContentAdSchemaListProcess2(oContentAdSchema);
        for (OContentAdSchema contentAdSchema : oContentAdSchemas) {
            String configValue = "10";
            String temp = Convert.toStr(redisService.getCacheObject(getCacheKey("ad_timeout")));

            if (temp != null) {
                configValue = temp;
            }
            Calendar nowTime = Calendar.getInstance();
            nowTime.setTime(contentAdSchema.getUpdateDate());
            nowTime.add(Calendar.MINUTE, Integer.parseInt(configValue));
            if(new Date().before(nowTime.getTime())){
                continue;
            }


            contentAdSchema.setRemarks("超时");
            oContentAdSchemaMapper.updateOContentAdSchema(contentAdSchema);
            try {
                processService.richProcessField(contentAdSchema);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject obj = new JSONObject();
            obj.put("comment", "发布失败");
            obj.put("pass", true);
            obj.put("publishResults", "02");
            obj.put("formData", contentAdSchema);
            processService.complete(contentAdSchema.getTaskId(), contentAdSchema.getInstanceId(), obj.toJSONString());
        }

        updateappStatus("f4");
        updateappStatus("f6");
        updateappStatus("f7");


        return 0;
    }

    public int updateappStatus(String processId) {
        OContentAppSchema contentAppSchema = new OContentAppSchema();
        contentAppSchema.setProcessId(processId);
        List<OContentAppSchema> list = oContentAppSchemaMapper.selectOContentAppSchemaListProcess1(contentAppSchema);
        for (OContentAppSchema appSchema : list) {
            String configValue = "120";
            String temp = Convert.toStr(redisService.getCacheObject(getCacheKey("app_timeout")));

            if (temp != null) {
                configValue = temp;
            }
            Calendar nowTime = Calendar.getInstance();
            nowTime.setTime(appSchema.getUpdateDate());
            nowTime.add(Calendar.MINUTE, Integer.parseInt(configValue));
            if(new Date().before(nowTime.getTime())){
                continue;
            }


            appSchema.setRemarks("超时");
            oContentAppSchemaMapper.updateOContentAppSchema(appSchema);
            try {
                processService.richProcessField(appSchema);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject obj = new JSONObject();
            obj.put("comment", "发布失败");
            obj.put("pass", true);
            obj.put("publishResults", "02");
            obj.put("formData", appSchema);
            processService.complete(appSchema.getTaskId(), appSchema.getInstanceId(), obj.toJSONString());
        }
        return 0;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }


//    public static void main(String[] args) {
//        String relativePath="测试370881200005134810/履历类材料/履历 001.jpg";
//        // 2. 获取路径的前一级
//        int index = relativePath.lastIndexOf("/");
//        System.out.println(index);
//        String tail = relativePath.substring(0, index);
//        System.out.println(tail);
//        int index1 = tail.lastIndexOf("/");
//        System.out.println(index1);
//        String last = tail.substring(index1+1);
//        System.out.println(last);
////        Log4jHelper.getLogger().info("挂接材料接口导入：前一级目录" + last);
//    }
}
